package com.xing.filter;

import cn.hutool.core.util.StrUtil;
import com.xing.Utils.TokenUtils;
import com.xing.cache.TokenStoreCache;
import com.xing.user.User;
import com.xing.user.UserDetail;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @version 1.0
 * @Author Xing
 * @Date 2023/12/5 14:22
 */
@Component
@AllArgsConstructor
public class JwtAuthtienticationTokenFilter extends OncePerRequestFilter {
    private final TokenStoreCache tokenStoreCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = TokenUtils.getAccesstoken(request);
//        System.out.println("打印了一下，表示有验证过程");
        // accessToken为空，表示未登录
        if (StrUtil.isBlank(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        User user = tokenStoreCache.getUser(token);
        if (user == null) {
            filterChain.doFilter(request, response);
            return;
        }
        ArrayList<SimpleGrantedAuthority> authorities = new ArrayList<>();

        for (String perm : user.getPower()) {
            authorities.add(new SimpleGrantedAuthority(perm));
        }
        // 用户存在
        Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, authorities);
//        System.out.println(authentication);
        // 新建 SecurityContext
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(authentication);
        SecurityContextHolder.setContext(context);

        filterChain.doFilter(request, response);
    }
}
